import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/home.dart';
import 'package:flutter_house_manager/pages/Home/components/home_list.dart';
import 'package:flutter_house_manager/pages/Home/components/home_nav.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:flutter_house_manager/utils/toast.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 社区公告列表 （从后端获取）
  List _announceList = [];
  @override
  void initState() {
    super.initState();
    getAnnounceList();
  }

  // 1.获取公告列表
  getAnnounceList() async {
    try {
      final data = await getAnnounceListAPI();
      setState(() {
        _announceList = data;
      });
      PromptAction.showSuccess('获取公告列表成功');
    } catch (e) {
      PromptAction.showError('获取公告列表失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('享+社区'),
      ),
      body: ListView(
        children: [
          // testToken(),
          // testTimer(),
          const HomeNav(),
          const SizedBox(
            height: 10,
          ),
          Image.asset('assets/images/banner@2x.jpg'),
          const SizedBox(
            height: 10,
          ),
          HomeList(list: _announceList),
        ],
      ),
    );
  }

  int _count = 60;
  Timer? _timer;
  testTimer() {
    return Row(
      children: [
        ElevatedButton(
            onPressed: () {
              if (_timer != null) {
                return;
              }
              _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
                setState(() {
                  _count--;
                });
              });
            },
            child: const Text('开始')),
        Text('$_count s'),
        ElevatedButton(
            onPressed: () {
              if (_timer != null) {
                _timer!.cancel();
                _timer = null;
              }
            },
            child: const Text('停止')),
      ],
    );
  }

  testToken() {
    return Row(
      children: [
        ElevatedButton(
            onPressed: () async {
              await tokenManager.setToken('123456');
              PromptAction.showSuccess('存储token成功');
            },
            child: const Text('存储token')),
        ElevatedButton(
            onPressed: () async {
              final token = tokenManager.getToken();
              PromptAction.showSuccess('token:$token');
            },
            child: const Text('获取token')),
        ElevatedButton(
            onPressed: () async {
              await tokenManager.removeToken();
              PromptAction.showSuccess('删除token成功');
            },
            child: const Text('删除token')),
      ],
    );
  }
}
